package com.situ.mall.controller;



import com.situ.common.util.PageResult;
import com.situ.common.util.Result;
import com.situ.mall.constant.RedisConstants;
import com.situ.mall.pojo.entity.Admin;
import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.query.AdminQuery;
import com.situ.mall.service.IAdminService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/list")
    @ResponseBody
    public PageResult list(AdminQuery adminQuery) {
        PageResult pageInfo = adminService.list(adminQuery);
        return pageInfo;
    }
    @RequestMapping("/login")
    @ResponseBody
    public Result login(AdminQuery adminQuery, HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(adminQuery.getCode())) {
            return Result.error("验证码错误");
        }
        Admin admin = adminService.login(adminQuery.getAccount(), adminQuery.getPassword());
        if (admin == null) {
            return Result.error("用户名或密码错误");
        }
        if (admin.getStatus() == 0) {
            return Result.error("该用户已经禁用，请联系管理员");
        }
        if (!ObjectUtils.isEmpty(adminQuery.getAutoLogin())) {
            Cookie cookie = new Cookie("autoLogin", admin.getAccount() + "&" + admin.getPassword());
            //设置Cookie 的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7);//设置时间为1周
            //cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie，返回给浏览器
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        session.setAttribute("admin", admin);
        return Result.ok("登录成功");
    }
    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        // 判断cookie是否为空
        if (!ObjectUtils.isEmpty(cookies)) {
            for (Cookie C : cookies) {
                // 获取cookie的name
                String name = C.getName();
                if ("autoLogin".equals(name)) {
                    cookie = C;
                    break;

                }
            }
        }
        if (!ObjectUtils.isEmpty(cookie)) {
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return Result.ok("退出成功");
    }
    @RequestMapping("/updateStatus")
    @ResponseBody
    public Result updateStatus(Admin admin) {
        adminService.update(admin);
        return Result.ok("修改成功！");
    }
    @RequestMapping("/updateRole")
    @ResponseBody
    public Result updateRole(Admin admin) {
        adminService.update(admin);
        return Result.ok("修改成功！");
    }
    @RequestMapping("/updateIsDeleted")
    @ResponseBody
    public Result updateIsDeleted(Admin admin) {
        adminService.update(admin);
        return Result.ok("修改成功！");
    }
    @RequestMapping("/add")
    @ResponseBody
    public Result add(Admin admin) {
        Integer accountCount = adminService.selectByAccount(admin);
        if (accountCount == 0) {
            adminService.add(admin);
            //将Product中真正使用的图片保存到Redis中
            redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getImage());
            return Result.ok("添加成功！");
        } else {
            return Result.error("账号已经存在！");
        }

    }
    @RequestMapping("/selectById")
    @ResponseBody
    public Result selectById(Integer id) {
        Admin admin = adminService.selectById(id);
        return Result.ok(admin);
    }
    @RequestMapping("/update")
    @ResponseBody
    public Result update(Admin admin) {
        Integer accountCount = adminService.selectByAccountId(admin);
        if (accountCount == 0) {
            adminService.update(admin);
            redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getImage());
            return Result.ok("修改成功！");
        } else {
            return Result.error("账号已经存在！");
        }

    }
    @RequestMapping("/deleteAll")
    @ResponseBody
    public Result deleteAll(Integer[] ids) {
        adminService.deleteAll(ids);
        return Result.ok("删除成功！");
    }
    @RequestMapping("/deleteById")
    @ResponseBody
    public Result deleteById(Integer id) {
        adminService.deleteById(id);
        return Result.ok("删除成功！");
    }
    @RequestMapping("/selectByInfoId")
    @ResponseBody
    public Result selectByInfoId(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        Admin adminInfo = adminService.selectById(admin.getId());
        return Result.ok(adminInfo);
    }
    @RequestMapping("/updatePassword")
    @ResponseBody
    public Result updatePassword(HttpServletRequest request, HttpServletResponse response, Admin admin, String newPassword) {
        HttpSession session = request.getSession();
        Admin adminSession = (Admin) session.getAttribute("user");
        Admin adminInfo = adminService.selectById(adminSession.getId());
        if (Objects.equals(admin.getPassword(), adminInfo.getPassword())) {
            adminService.updatePassword(admin.getId(), newPassword);

            session.removeAttribute("admin");
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            // 判断cookie是否为空
            if (!ObjectUtils.isEmpty(cookies)) {
                for (Cookie C : cookies) {
                    // 获取cookie的name
                    String name = C.getName();
                    if ("autoLogin".equals(name)) {
                        cookie = C;
                        break;

                    }
                }
            }
            if (!ObjectUtils.isEmpty(cookie)) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            return Result.ok("退出成功");
        } else {
            return Result.error("原密码错误！");
        }

    }
}
